package com.ljkj.blockpay.network.interceptor;


import android.annotation.SuppressLint;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.camera.core.Logger;

import com.ljkj.blockpay.basedata.BaseModel;
import com.ljkj.blockpay.util.JsonUtil;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;


/**
 * @Description: An OkHttp interceptor which logs request and response information. Can be applied as an
 * OkHttpClient#networkInterceptors() network interceptor}. <p> The format of the logs created by
 * this class should not be considered stable and may change slightly between releases. If you need
 * a stable logging format, use your own interceptor.
 */
public final class HttpLoggingInterceptor implements Interceptor {
    private static final String TAG = "StarNetwork";

    @SuppressLint("RestrictedApi")
    @NonNull
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        //计算接口响应的时间（已注释）
        long startNs = System.nanoTime();
        Response response = chain.proceed(request);
        long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
        ResponseBody responseBody = response.body();
        String bodyString = responseBody != null ? responseBody.string() : "";
        Logger.d(TAG, "HTTP code:" + response.code() + "    " + tookMs + "ms" + "    ");
        long contentLength = responseBody != null ? responseBody.contentLength() : 0;
        Logger.d(TAG, "ContentLength:  " + contentLength + " Bytes");
//        Logger.d("okhttp:",bodyString);
        try {
            BaseModel baseModel = JsonUtil.jsonToObj(bodyString, BaseModel.class);
            if (!baseModel.isSuccess()) {
                if (!TextUtils.isEmpty(bodyString)) {
                    Log.w(TAG, bodyString);
                }
//                String url = request.url().toString();
//                EventBus.getDefault().postSticky(new HttpRequestErrorEvent(url, baseModel.code));
            }
        } catch (Exception e) {
            Log.d(TAG, "<<<<<<<<<<<<<<<<  HTTP FAILED  <<<<<<<<<<<<<<<<\n" + e + "\n\n\n" + " ");
            e.printStackTrace();
        }
        MediaType contentType = responseBody != null ? responseBody.contentType() : null;
        return response.newBuilder().body(ResponseBody.create(contentType, bodyString != null ? bodyString : "")).build();
    }
}
